package cn.yzx.pethome.system.login.controller;

import cn.yzx.pethome.constants.BaseConstants;
import cn.yzx.pethome.system.login.domain.MsgLogin;
import cn.yzx.pethome.system.user.domain.User;
import cn.yzx.pethome.system.user.service.IUserService;
import cn.yzx.pethome.utils.AjaxResult;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/login")
//这里是说明你这个类是干什么用的
@Api(value = "登录API",description="登录的功能")
public class LoginController {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private IUserService userService;
    @PostMapping("/msg")
    public AjaxResult loginMsg(@RequestBody MsgLogin msg){
        //判断数据
        if (msg.getPhone() == null){
            return AjaxResult.error().setMsg("手机号不能为空");
        }
        if (msg.getPhoneCode() == null){
            return AjaxResult.error().setMsg("验证码不能为空");
        }
        //判断手机号是否注册
        User user = userService.findByPhone(msg.getPhone());
        if (user == null){
            return AjaxResult.error().setMsg("该手机号还未被注册，请注册后登录");
        }
        //判断验证码是否失效
        //获取key
        String key = msg.getPhone() + BaseConstants.Login.LOGIN;
        Object o = redisTemplate.opsForValue().get(key);
        if (o==null){
            return AjaxResult.error().setMsg("验证码已失效,请重新获取验证码");
        }else if (!o.toString().equals(msg.getPhoneCode())){
            return AjaxResult.error().setMsg("验证码错误");
        }
        return AjaxResult.success();
    }
}
